<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <img ref="img" src="@/assets/images/avatar.jpg" alt="" />
    <div class="mybtn">
      <input ref="abcc" type="file" style="display: none" @change="inpchange" />
      <el-button type="primary" icon="el-icon-plus" @click="getpic">选择图片</el-button>
      <el-button ref="btn" type="success" icon="el-icon-upload" @click="shangchuan" :disabled="flag"
        >上传头像</el-button
      >
    </div>
  </el-card>
</template>

<script>
import { updatePicAPI } from '@/api/user'
export default {
  data() {
    return {
      userPic: {
        avatar: ''
      },
      flag: true
    }
  },

  methods: {
    getpic() {
      this.$refs.abcc.click()
    },
    inpchange() {
      if (this.$refs.abcc.files.length > 0) {
        const fl = this.$refs.abcc.files[0]
        const fr = new FileReader()
        fr.readAsDataURL(fl)
        fr.onload = () => {
          this.$refs.img.src = fr.result

          this.userPic.avatar = fr.result
          this.$nextTick(() => {
            this.flag = false
          })
        }
      }
    },
    async shangchuan() {
      const { data: res } = await updatePicAPI(this.userPic)
      if (res.code === 0) {
        this.$message.success(res.message)

        this.$store.dispatch('user/getUser')
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.mybtn {
  margin-top: 10px;
}
img {
  width: 350px;
  height: 350px;
  object-fit: cover;
}
</style>
